<template>
  <div class="container">
    <topTitle :titleText="titleText" :titleExplain="titleExplain"></topTitle>
    <div class="mainCon mainBox">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="ruleForm"
        status-icon
        aria-autocomplete="false"
        label-width="164px"
      >
        <el-form-item label="企业名称：" prop="companyName">
          <el-input
            class="lWidth"
            v-model.trim="ruleForm.companyName"
            placeholder="输入企业名称"
            clearable
            @blur="ruleForm.companyName = changeValue($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码：" prop="uscc">
          <el-input
            class="mWidth"
            v-model.trim="ruleForm.uscc"
            placeholder="输入统一社会信用代码"
            clearable
            @blur="ruleForm.uscc = changeValue($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业所属行业：">
          <el-cascader
            class="lWidth"
            ref="industry"
            v-model="ruleForm.industry"
            :options="industryOptions"
            filterable
            @change="getIndustry"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="企业人员规模：">
          <el-select
            class="sWidth"
            v-model="ruleForm.scale"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in scaleSelct"
              :key="index"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业归属：" class="radioBox">
          <el-radio-group v-model="ruleForm.belong" @change="changeBelong">
            <el-radio label="1">本地企业</el-radio>
            <el-radio label="2">外地企业</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业注册地址：" prop="regAddress">
          <el-cascader
            ref="regAreas"
            class="mWidth"
            :key="isShowRegArea"
            v-model="ruleForm.regAddress"
            :options="regAreasOptions"
            @change="handerChange"
            clearable
            filterable
            placeholder="请选择营业执照上的注册地址"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="企业经营地址："
          prop="manageAddress"
          v-if="ruleForm.belong === '2'"
        >
          <el-cascader
            ref="manageAreas"
            class="mWidth"
            :key="isShowManaArea"
            v-model="ruleForm.manageAddress"
            :options="areasOptions"
            clearable
            filterable
            placeholder="请选择企业在本地经营场所地址"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="企业经营地址：" prop="address" v-else>
          <el-input
            v-model.trim="ruleForm.address"
            class="mWidth"
            placeholder="请选择企业在本地经营场所地址"
            disabled
            @blur="ruleForm.address = changeValue($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="密保手机号：" prop="phone">
          <el-input
            v-model.trim="ruleForm.phone"
            class="mWidth"
            placeholder="用于接收审核结果和后期账号安全设置"
            clearable
            @blur="ruleForm.phone = changeValue($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="企业资料：" class="imgLabel">
          <ul class="imgBoxs clearfix">
            <li class="imgBox">
              <div class="imgTopBox">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="点击上传图片"
                  placement="bottom"
                >
                  <form class="uploadBtn" id="licenseForm">
                    <input
                      type="file"
                      name="file"
                      id="licenseFile"
                      accept="image/png, image/jpeg, image/jpg"
                      @change="
                        uploadImg('licenseFile', 0, 'licenseForm', 'LICENSE')
                      "
                    />
                    <i class="el-icon-plus"></i>
                    <img :src="file[0].imgSrc" v-show="file[0].isShow" />
                  </form>
                </el-tooltip>
                <div class="imgName">企业营业执照</div>
              </div>
              <el-button type="text" @click="licenseDialog = true"
                >示例图</el-button
              >
            </li>
            <li class="imgBox">
              <div class="imgTopBox">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="点击上传图片"
                  placement="bottom"
                >
                  <form class="uploadBtn" id="idcardForm1">
                    <input
                      type="file"
                      name="file"
                      id="idcardFront"
                      accept="image/png, image/jpeg, image/jpg"
                      @change="
                        uploadImg(
                          'idcardFront',
                          1,
                          'idcardForm1',
                          'IDCARDFRONT'
                        )
                      "
                    />
                    <i class="el-icon-plus"></i>
                    <img :src="file[1].imgSrc" v-show="file[1].isShow" />
                  </form>
                </el-tooltip>
                <div class="imgName">法人身份证正面</div>
              </div>
              <el-button type="text" @click="idcardDialog1 = true"
                >示例图</el-button
              >
            </li>
            <li class="imgBox">
              <div class="imgTopBox">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="点击上传图片"
                  placement="bottom"
                >
                  <form class="uploadBtn" id="idcardForm2">
                    <input
                      type="file"
                      name="file"
                      id="idcardBack"
                      accept="image/png, image/jpeg, image/jpg"
                      @change="
                        uploadImg('idcardBack', 2, 'idcardForm2', 'IDCARDBACK')
                      "
                    />
                    <i class="el-icon-plus"></i>
                    <img :src="file[2].imgSrc" v-show="file[2].isShow" />
                  </form>
                </el-tooltip>
                <div class="imgName">法人身份证反面</div>
              </div>
              <el-button type="text" @click="idcardDialog2 = true"
                >示例图</el-button
              >
            </li>
          </ul>
        </el-form-item>
        <el-form-item
          style="text-align: left; margin-top: 6px; margin-bottom: 0"
        >
          <el-button
            type="primary"
            size="medium"
            class="commonBut saveBtn"
            @click="submitForm('ruleForm')"
            :loading="isSubmit"
            >建档企业</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      title="营业执照示例图"
      :visible.sync="licenseDialog"
      width="500px;"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/license.jpg" width="400px;" />
    </el-dialog>
    <el-dialog
      title="身份证正面示例图"
      :visible.sync="idcardDialog1"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/idcard2.jpg" width="400px;" />
    </el-dialog>
    <el-dialog
      title="身份证反面示例图"
      :visible.sync="idcardDialog2"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <img src="../../../static/img/register/idcard1.jpg" width="400px;" />
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'

export default {
  name: 'accountAssignment',
  data() {
    //验证企业名称
    var validateName = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('企业名称不能为空'))
      } else {
        if (value.length > 100) {
          callback(new Error('企业名称不能超过100个字符'))
        } else {
          if (this.ruleForm.uscc !== '') {
            this.$refs.ruleForm.validateField('uscc')
          }
          callback()
        }
      }
    }
    //验证uscc
    var validateUscc = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('统一社会信用代码不能为空'))
      } else {
        var regUscc = /^[0-9A-Z]{2}[0-9]{6}[0-9A-Z]{10}$/
        if (!regUscc.test(value)) {
          callback(new Error('统一社会信用代码格式不正确'))
        } else {
          this.axios({
            method: 'post',
            url: 'api-c/companyaudit/base/validcompanyuscc',
            data: {
              name: this.ruleForm.companyName.replace(/\s+/g, ''),
              uscc: value,
            },
          })
            .then((res) => {
              if (!res.data.hasError) {
                callback()
              } else {
                callback(new Error(res.data.errorMsg))
              }
            })
            .catch((error) => {
              callback(new Error('企业信息校验失败，请稍后重试'))
            })
        }
      }
    }
    //验证手机号码
    var validatePhone = (rule, value, callback) => {
      value = value.replace(/\s+/g, '')
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else {
        var regTel = /^1[3456789]\d{9}$/
        if (!regTel.test(value)) {
          callback(new Error('手机号码格式不正确'))
        } else {
          this.noTel = false
        }
        callback()
      }
    }
    return {
      titleText: '企业建档',
      titleExplain:
        '施工方及建设方企业可由监管部门进行建档，建档完成后即可自动分配企业账号至该企业，相关施工方及建设方即可登录管理项目',
      noTel: true,
      isSubmit: false, //提交按钮禁止点击
      licenseDialog: false, //营业执照示例图
      idcardDialog1: false, //身份证示例图
      idcardDialog2: false, //身份证示例图
      isShowRegArea: 0,
      isShowManaArea: 0,
      industryOptions: [], //行业数据
      outAreasOptions: [], //省外省市
      neiAreasOptions: [], //内蒙省市
      areasOptions: [], //经营地址
      regAreasOptions: [], //注册地址
      regAreas: {
        regAreaId: '', //注册地址全id
      },
      manageAreas: {
        bizAreaId: '', //经营地址全id
      },
      scaleSelct: [
        {
          label: '51-100人',
          value: '02',
        },
        {
          label: '101-200人',
          value: '03',
        },
        {
          label: '201-500人',
          value: '04',
        },
        {
          label: '501-1000人',
          value: '05',
        },
        {
          label: '1000人以上',
          value: '06',
        },
      ],
      rules: {
        companyName: [
          { required: true, validator: validateName, trigger: 'blur' },
        ],
        uscc: [
          {
            required: true,
            validator: validateUscc,
            trigger: 'change',
          },
        ],
        regAddress: [
          {
            required: true,
            message: '请选择注册地址',
            trigger: 'change',
          },
        ],
        manageAddress: [
          {
            required: true,
            message: '请输入经营地址',
            trigger: 'change',
          },
        ],
        address: [
          {
            required: true,
            message: '请输入经营地址',
            trigger: 'change',
          },
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur',
          },
        ],
      },
      ruleForm: {
        companyName: '',
        uscc: '',
        industry: '',
        scale: '',
        belong: '1',
        regAreaId: [],
        bizAreaId: [], //本省经营地址
        manageAddress: [], //外省经营地址
        regAddress: [],
        address: '',
        phone: '',
      },
      file: [
        {
          //上传图片
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'LICENSE', //新文件名(营业执照)
          FileSize: '', //文件大小
          FileType: '', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
        {
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'IDCARDFRONT', //新文件名(身份证)
          FileSize: '', //文件大小
          FileType: '', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
        {
          originalName: '', //原文件名
          imgId: '', //图片id
          newName: 'IDCARDBACK', //新文件名(身份证)
          FileSize: '', //文件大小
          FileType: '', //文件类型
          relativePath: '', //文件相对路径
          imgSrc: '', //文件绝对路径
          isShow: false,
        },
      ],
    }
  },
  created() {
    //获取行业
    this.selectIndustry()
    //获取内蒙省市
    this.selectNeiAreas()
    //获取全国省市除内蒙
    this.selectOutAreas()
  },
  methods: {
    //改变企业归属
    changeBelong(value) {
      //（本省：1，外省：2）
      if (value === '1') {
        ++this.isShowRegArea
        this.regAreasOptions = this.neiAreasOptions
        this.ruleForm.address = ''
        this.$refs.ruleForm.validateField('address', (Error) => {})
      } else {
        ++this.isShowRegArea
        ++this.isShowManaArea
        this.regAreasOptions = this.outAreasOptions
        this.ruleForm.manageAddress = []
        this.$refs.ruleForm.validateField('manageAddress', (Error) => {})
      }
      this.ruleForm.regAddress = []
      this.$refs.ruleForm.validateField('regAddress', (Error) => {})
    },
    //请求行业
    selectIndustry() {
      let vm = this
      vm.axios({
        method: 'post',
        url: 'api-bs/industry/base/detailbyindustryid',
      })
        .then((res) => {
          vm.industryOptions = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    //获取内蒙省市
    selectNeiAreas() {
      let vm = this
      //（本省：1，外省：2）
      vm.axios({
        method: 'post',
        url: 'api-bs/areadic/base/areas',
        data: {
          belongs: 1,
          areaId: this.$store.state.areaInfoArr.areaId,
        },
      })
        .then(
          (res) => {
            ++vm.isShowRegArea
            ++vm.isShowManaArea
            //内蒙省市
            if (!res.data.hasError) {
              vm.neiAreasOptions = res.data.result
              vm.regAreasOptions = res.data.result
              vm.areasOptions = res.data.result
            } else {
              this.$message({
                showClose: true,
                duration: 3000,
                message: '获取区域数据失败',
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取区域数据失败',
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    //获取省外省市
    selectOutAreas() {
      let vm = this
      //（本省：1，外省：2）
      vm.axios({
        method: 'post',
        url: 'api-bs/areadic/base/areas',
        data: {
          belongs: 2,
          areaId: this.$store.state.areaInfoArr.areaId,
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            vm.outAreasOptions = res.data.result
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取区域数据失败',
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取区域数据失败',
            type: 'error',
          })
        })
    },
    //本省企业经营地址等于注册地址
    handerChange(item) {
      if (this.ruleForm.regAddress.length > 0) {
        if (this.ruleForm.belong === '1') {
          let regAreaArray = this.$refs.regAreas.getCheckedNodes()[0].pathLabels
          if (regAreaArray.length > 1) {
            this.ruleForm.address = regAreaArray[0] + ' / ' + regAreaArray[1]
          } else {
            this.ruleForm.address = regAreaArray[0]
          }
        }
      }
    },
    //获取所属行业
    getIndustry() {
      if (this.ruleForm.industry.length > 0) {
        this.ruleForm.industry =
          this.$refs.industry.getCheckedNodes()[0].path[1]
      }
    },
    //获取注册地址的省市区
    getRegAddress() {
      let path = this.$refs.regAreas.getCheckedNodes()[0].path
      let address = this.$refs.regAreas.getCheckedNodes()[0].pathLabels
      this.regAreas.regAreaId = this.$refs.regAreas.getCheckedNodes()[0].value
    },
    //获取经营地址的市区
    getManageAddress() {
      if (this.ruleForm.belong === '1') {
        //内蒙经营地址
        this.manageAreas.bizAreaId = this.regAreas.regAreaId
      } else {
        //外省地址
        this.manageAreas.bizAreaId =
          this.$refs.manageAreas.getCheckedNodes()[0].value
      }
    },
    //图片上传
    ajaxUpload(formName, index, imgName) {
      var vm = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'post',
        dataType: 'json',
        success: function (data) {
          vm.file[index].originalName = data.name
          vm.file[index].imgId = data.id
          vm.file[index].newName = data.id + imgName
          vm.file[index].FileSize = data.size
          vm.file[index].FileType = data.contentType
          vm.file[index].relativePath = data.path
          vm.file[index].imgSrc = data.url
          vm.file[index].isShow = true
        },
        error: function () {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片上传失败',
            type: 'error',
          })
        },
      }
      $('#' + formName).ajaxSubmit(options)
      return false
    },
    //上传图片
    uploadImg(inputId, index, formName, imgName) {
      var vm = this
      var fileName
      var file
      var fileSize
      try {
        fileName = $('#' + inputId).val()
        file = $('#' + inputId)[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过5M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      if (fileName) {
        //判断图片类型
        if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(fileName)) {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片类型必须是jpeg，jpg，png中的一种',
            type: 'error',
          })
          $('#' + inputId).val('')
          return
        }
        //判断图片大小
        if (fileSize / 1 > 1024 * 5) {
          vm.$message({
            showClose: true,
            duration: 3000,
            message: '图片大小不能超过5M',
            type: 'error',
          })
          $('#' + inputId).val('')
          return
        }
        vm.ajaxUpload(formName, index, imgName)
      }
    },
    //获取图片数组
    getImg() {
      let vm = this
      const fileArray = new Array()
      for (var j = 0; j < vm.file.length; j++) {
        fileArray[j] = {
          originalName: vm.file[j].originalName,
          newName: vm.file[j].imgId + vm.file[j].newName,
          FileSize: vm.file[j].FileSize,
          FileType: vm.file[j].FileType,
          relativePath: vm.file[j].relativePath,
        }
      }
      return JSON.stringify(fileArray)
    },
    //提交申请
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取注册地址的省市区
          this.getRegAddress()
          //获取经营地址的市区
          this.getManageAddress()
          this.submitRequest()
        }
      })
    },
    //提交表单请求
    submitRequest() {
      let vm = this
      vm.isSubmit = true
      vm.axios({
        method: 'post',
        url: 'api-c/companyaudit/expand/addcompanynoapproval',
        data: {
          name: vm.ruleForm.companyName,
          uscc: vm.ruleForm.uscc,
          industryId: vm.ruleForm.industry,
          scale: vm.ruleForm.scale,
          belongs: vm.ruleForm.belong,
          regAreaId: vm.regAreas.regAreaId, // --注册地址全id
          bizAreaId: vm.manageAreas.bizAreaId, //   ---经营地址全id
          tel: vm.ruleForm.phone,
          fileVOs: vm.getImg(),
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                message: res.data.msg,
                type: 'success',
              })
              this.$refs['ruleForm'].resetFields()
              this.ruleForm.industry = ''
              this.ruleForm.scale = ''
              this.file[0].imgSrc = ''
              this.file[1].imgSrc = ''
              this.file[2].imgSrc = ''
              this.file[0].isShow = false
              this.file[1].isShow = false
              this.file[2].isShow = false
            } else {
              this.$message({
                showClose: true,
                message: res.data.errorMsg,
                type: 'error',
              })
            }
            vm.isSubmit = false
          },
          (res) => {
            this.$message({
              showClose: true,
              duration: 3000,
              message: '提交失败',
              type: 'error',
            })
            vm.isSubmit = false
          }
        )
        .catch((error) => {})
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  padding: 24px;
  // text-align: center;
  .ruleForm {
    // width: 500px;
    // display: inline-block;
    // .el-select {
    //     width: 100%;
    // }
    padding: 16px 36px;
    // .industrySelect {
    //     width: 360px;
    // }
    .areasSelect {
      width: 360px;
    }
    .radioBox /deep/.el-form-item__content {
      text-align: left;
    }
  }
  .registerBtn {
    margin-top: 0px;
  }
  .el-dialog img {
    width: 100%;
  }
}
.alignCenter {
  text-align: center;
}
.registered {
  text-align: center;
  padding: 50px 100px;
  margin-top: 5%;
  .messageRemind {
    margin-bottom: 25px;
    color: #666;
    font-size: 14px;
    margin-top: 20px;
  }
}
//上传图片样式
.imgBoxs {
  .imgBox {
    text-align: center;
    float: left;
    margin-right: 15px;
    font-size: 12px;
    .imgTopBox {
      width: 104px;
      height: 104px;
      border: 1px dotted #d4dae6;
      position: relative;
      background-color: #f5f7fb;
      .uploadBtn {
        width: 102px;
        height: 73px;
        cursor: pointer;
        input {
          opacity: 0;
          position: absolute;
          left: 0;
          top: 0;
          z-index: 100;
          height: 74px;
          width: 104px;
        }
        i {
          line-height: 74px;
          font-size: 25px;
          color: #b5b6b7;
        }
        img {
          width: 102px;
          height: 73px;
          position: absolute;
          top: 0;
          left: 0;
        }
      }
      .imgName {
        height: 30px;
        line-height: 30px;
        background: rgba(206, 206, 206, 0.3);
        color: #aaa;
      }
    }
  }
}
/deep/.el-dialog__body {
  max-height: fit-content;
  text-align: center;
}
</style>
